package com.happe.foodeasy.winter.conf.parser;

import com.happe.foodeasy.helper.ClassOperateHelper;
import com.happe.foodeasy.winter.helper.ConfigurationFilesParserHelper;

import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.concurrent.Callable;

/**
 * This class has the skeleton of callable task for parsing properties' files.
 * Created by wubin on 2016-05-19.
 */
abstract class PropertiesFileParseTaskCallable<T> implements Callable<T> {
    @Override
    @SuppressWarnings("all")
    public T call() throws Exception {
        FileReader reader = new FileReader(retrieveParseFilePath());
        Properties properties = new Properties();
        properties.load(reader);
        Class<T> tClass = retrieveParseResultType();
        Class builderClass = ClassOperateHelper.retrieveTargetInnerClassInClass(tClass, "Builder");

        if (builderClass == null) {
            throw new RuntimeException("在" + tClass.getName() + "找不到指定的内部类: Builder");
        }

        Object builderEntity = ClassOperateHelper.createTargetInstance(builderClass, ConfigurationFilesParserHelper.properties2Map(properties));
        Method buildMethod = builderClass.getDeclaredMethod("build");
        return (T) buildMethod.invoke(builderEntity);
    }

    protected abstract Class<T> retrieveParseResultType();

    protected abstract String retrieveParseFilePath();
}
